<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 丑小鸭
 -->

<template>
  <div>
    <van-form class="duck">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field v-model="ruleForm.pwd" type="password" label="密码" placeholder="请填写密码" clearable />
      <!-- 验证码 -->
      <div class="popup-open__form-code">
        <van-field
          v-model="ruleForm.captcha"
          type="tel"
          label="验证码"
          placeholder="请填写验证码"
          clearable
        />
        <van-image :src="imageSrc" @click="onGetCaptcha">
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import * as duck from "@/api/duck";
import * as api from "@/api/index";
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "Duck",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    content: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        mobile: "",
        pwd: "",
        captchaKey: "",
        captcha: ""
      },
      // 图形验证码
      imageSrc: "",
      // 循环时间
      IntervalTime: 8,
      // 任务类型
      type: "0",
      typeOptions: [
        { label: "先款任务", type: "0" },
        { label: "垫付任务", type: "1" }
      ],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      taskType: "",
      // 接口返回提示
      returnContent: [],
      // 接单接口
      getTaskUrl: duck.getTaskList,
      getAcceptTaskUrl: duck.getAcceptTask,
      // 已有平台
      iconItems: [],
      // 请求头
      headers: "",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听type
    taskType(val) {
      this.getAcceptTaskUrl =
        val == 2 ? duck.getFlowAcceptTask : duck.getAcceptTask;
    },
    // 监听接单状态
    startFlag() {
      if (this.item.index === 1 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 1 && this.index !== "") {
        this.onGetCaptcha();
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.mobile = this.item.user;
        this.ruleForm.pwd = this.item.pass;
        this.type = this.item.type || "0";
        this.startFlag = this.item.startFlag;
        this.returnContent = this.item.content;
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    },
    returnContent() {
      if (this.item.index === 1) {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.startFlag ? "已启动" : "待启动",
          content: this.returnContent
        });
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    }
  },
  created() {
    if (this.item.index === 1 && this.index !== "") {
      this.onGetCaptcha();
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.mobile = this.item.user;
      this.ruleForm.pwd = this.item.pass;
      this.type = this.item.type || "0";
      this.startFlag = this.item.startFlag;
      this.returnContent = this.item.content;
    }
  },
  methods: {
    // 获取验证码
    onGetCaptcha() {
      this.imageSrc = "";
      this.ruleForm.captchaKey = api.getString32();
      this.$axios.get(duck.getImg + this.ruleForm.captchaKey).then(() => {
        this.imageSrc = duck.getImg + this.ruleForm.captchaKey;
      });
    },
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.headers = "";
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          headers: "",
          data: this.ruleForm
        };
        duck.ajaxFun(duck.getLogin, param, res => {
          if (res) {
            _this.returnContent.unshift(alertMsg(res.msg));
            if (res.code === 2000) {
              // 登录成功  => 保存账号信息
              saveInfo({
                user: _this.ruleForm.mobile,
                pass: _this.ruleForm.pwd,
                type: _this.type,
                index: _this.index
              });
              _this.startFlag = true;
              _this.headers = {
                "x-rn-access-token": res.data.accessToken,
                "x-rn-platform": res.data.platform,
                "x-rn-user-id": res.data.userId
              };
              // 获取任务
              _this.returnContent.unshift(alertMsg("正在获取任务..."));
              _this.onGetTaskList(_this);
            } else {
              _this.startFlag = false;
            }
          } else {
            _this.returnContent.unshift(alertMsg("请重新登录..."));
            _this.onGetCaptcha();
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 任务列表
    onGetTaskList(_this) {
      clearInterval(_this.timer);
      _this.taskId = "";
      _this.$axios
        .post(
          _this.getTaskUrl,
          {
            // type: _this.type == 0 ? "" : 2,
            cancelFlag: 0,
            flowTypeFlag: 0,
            payWay: _this.type
          },
          {
            headers: _this.headers
          }
        )
        .then(res => {
          if (res.data.code === 2000) {
            // 接单
            _this.taskId = res.data.data.list[0].id;
            _this.taskType = res.data.data.list[0].type;
            _this.onGetOrder(_this);
          } else if (res.data.code === 0) {
            // 暂无数据 => 循环请求
            _this.returnContent.unshift(
              alertMsg("暂无合适的任务，持续接单中...")
            );
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetTaskList(_this);
              }
            }, _this.IntervalTime * 1000);
          } else {
            _this.startFlag = false;
          }
        })
        .catch(() => {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetTaskList(_this);
            }
          }, _this.IntervalTime * 1000);
        });
    },
    // 接单
    onGetOrder(_this) {
      _this.$axios
        .post(
          _this.getAcceptTaskUrl,
          qs.stringify({
            taskId: _this.taskId
          }),
          {
            headers: _this.headers
          }
        )
        .then(res => {
          if (res.data.code === 2000) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          } else {
            _this.returnContent.unshift(alertMsg(res.data.msg));
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetTaskList(_this);
              }
            }, _this.IntervalTime * 1000);
          }
        })
        .catch(() => {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetTaskList(_this);
            }
          }, _this.IntervalTime * 1000);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>

<style lang="scss">
.home-task {
  .van-dialog {
    border-radius: 5px !important;
    .van-field__body {
      background: #fafafa;
      .van-field__control {
        padding-left: 10px;
      }
    }
    .van-field__right-icon {
      @include flex();
    }
  }
}
</style>